<template>
  <n-card :bordered="false" class="proCard">
    <!-- 搜索表单 -->
    <BasicForm @register="registerForm" @submit="handleSearch" @reset="handleReset" :schemas="searchSchemas"
      :grid-props="{ cols: '1 s:1 m:2 l:3 xl:4 2xl:4', responsive: 'screen', xGap: 18 }" :label-width="80"
      :show-advanced-button="true" :collapsed-rows="2" layout="inline" :show-reset-button="true"
      :show-submit-button="true" submit-button-text="搜索" reset-button-text="重置" class="search-form" />

    <!-- 表格 -->
    <BasicTable title="账单记录" titleTooltip="显示所有账单记录信息" :columns="columns" :request="loadDataTable"
      :row-key="(row) => row.id" ref="actionRef" :scroll-x="1200" @update:checked-row-keys="onCheckedRow" />
  </n-card>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick } from 'vue';
import { BasicTable } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form';
import { getBillingRecords } from '@/api/billing';
import { columns } from './columns';

const actionRef = ref();
const [registerForm, { getFieldsValue, setFieldsValue, resetFields }] = useForm();

// 基础参数
const params = reactive({
  pageSize: 10,
  unique_str: 'customer_E590CEED9FE274220DF432712AA3F6DE',
});

// 搜索表单配置
const searchSchemas: FormSchema[] = [
  {
    field: 'account_id',
    label: '账户ID',
    component: 'NInput',
    componentProps: {
      placeholder: '请输入账户ID',
      clearable: true,
    },
  },
  {
    field: 'type',
    label: '类型',
    component: 'NSelect',
    componentProps: {
      placeholder: '请选择类型',
      clearable: true,
      options: [
        { label: '充值', value: 'RECHARGE' },
        { label: '提现', value: 'WITHDRAW' },
        { label: '转账', value: 'TRANSFER' },
        { label: '退款', value: 'REFUND' },
      ],
    },
  },
  {
    field: 'status',
    label: '状态',
    component: 'NSelect',
    componentProps: {
      placeholder: '请选择状态',
      clearable: true,
      options: [
        { label: '成功', value: 'done' },
        { label: '失败', value: 'fail' },
        { label: '处理中', value: 'init' },
      ],
    },
  },
  {
    field: 'day',
    label: '账单日期',
    component: 'NDatePicker',
    componentProps: {
      type: 'date',
      clearable: true,
      placeholder: '选择账单日期',
      format: 'yyyy-MM-dd',
      valueFormat: 'yyyyMMdd',
    },
  },
];

const loadDataTable = async (res: any) => {
  // 从 BasicForm 获取搜索参数
  const formValues = getFieldsValue();
  const searchFilters: any = {};

  if (formValues.account_id) {
    searchFilters.account_id = formValues.account_id;
  }

  if (formValues.type) {
    searchFilters.type = formValues.type;
  }

  if (formValues.status) {
    searchFilters.status = formValues.status;
  }

  if (formValues.day) {
    // 将日期转换为 yyyyMMdd 格式
    const date = new Date(formValues.day);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    searchFilters.day = `${year}${month}${day}`;
  }

  const requestParams = {
    ...params,
    ...searchFilters,
    page: res.page || 1,
    pageSize: res.pageSize || 10,
  };

  try {
    const response = await getBillingRecords(requestParams);

    console.log('API响应数据:', response); // 调试日志

    // 检查响应状态
    if (response && typeof response === 'object' && 'code' in response) {
      const { code, message, data } = response as any;

      // 如果返回错误码，显示错误提示
      if (code !== 200 && code !== 0) {
        // @ts-ignore
        window.$message?.error(message || '获取账单记录失败');
        return {
          list: [],
          page: 1,
          pageSize: 10,
          pageCount: 0,
          itemCount: 0,
        };
      }

      // 成功时处理数据 - data 字段包含分页信息和实际数据
      return {
        list: data?.data || [],
        page: data?.current_page || 1,
        pageSize: data?.per_page || 10,
        pageCount: data?.last_page || 1,
        itemCount: data?.total || 0,
      };
    }

    // 异常情况：响应格式不正确
    console.warn('响应格式异常:', response);
    // @ts-ignore
    window.$message?.error('响应数据格式异常');
    return {
      list: [],
      page: 1,
      pageSize: 10,
      pageCount: 0,
      itemCount: 0,
    };
  } catch (error) {
    console.error('获取账单记录失败:', error);

    // 显示错误提示
    // @ts-ignore
    window.$message?.error('获取账单记录失败，请稍后重试');

    return {
      list: [],
      page: 1,
      pageSize: 10,
      pageCount: 0,
      itemCount: 0,
    };
  }
};

// 搜索功能
const handleSearch = () => {
  actionRef.value?.reload();
};

// 重置搜索条件
const handleReset = () => {
  // 使用 nextTick 确保在下一个事件循环中执行，避免死锁
  nextTick(() => {
    try {
      // 手动清空表单值
      setFieldsValue({
        account_id: '',
        type: null,
        status: null,
        day: null,
      });
      // 重新加载表格
      actionRef.value?.reload();
    } catch (error) {
      console.error('重置失败:', error);
    }
  });
};

function onCheckedRow(rowKeys: any) {
  console.log('选中的行:', rowKeys);
}
</script>

<style lang="less" scoped>
.search-form {
  margin-bottom: 16px;
}
</style>